package com.doctor.windflower_doctor.receiver;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.alibaba.fastjson.JSON;
import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.SystemApplication;
import com.doctor.windflower_doctor.activity.MainActivity;
import com.doctor.windflower_doctor.entity.NotificationBeen;
import com.doctor.windflower_doctor.fragment.MenuFragment;
import com.doctor.windflower_doctor.util.LogUtils;
import com.tencent.android.tpush.XGPushBaseReceiver;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushRegisterResult;
import com.tencent.android.tpush.XGPushShowedResult;
import com.tencent.android.tpush.XGPushTextMessage;

public class FengxzNotificationReceiver extends XGPushBaseReceiver {
	private NotificationManager notiManager;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {

			super.dispatchMessage(msg);

		}
	};

	/**
	 * 删除标签结果
	 */
	@Override
	public void onDeleteTagResult(Context context, int errorCode, String tagName) {

	}

	/**
	 * 通知被打开触发的结果
	 */
	@Override
	public void onNotifactionClickedResult(Context context, XGPushClickedResult message) {
		LogUtils.e("FengxzNotificationReceiver================onNotifactionClickedResult");
		if (context == null || message == null) {
			return;
		}
		if (message.getActionType() == XGPushClickedResult.NOTIFACTION_CLICKED_TYPE) {
			// 通知在通知栏被点击啦。。。。。
			// APP自己处理点击的相关动作
			// 这个动作可以在activity的onResume也能监听，请看第3点相关内容
		} else if (message.getActionType() == XGPushClickedResult.NOTIFACTION_DELETED_TYPE) {
			// 通知被清除啦。。。。
			// APP自己处理通知被清除后的相关动作
		}

	}

	/**
	 * 通知被展示触发的结果，可以在此保存APP收到的通知
	 */
	@Override
	public void onNotifactionShowedResult(Context context, XGPushShowedResult notifiShowedRlt) {

	}

	/**
	 * 注册结果
	 */
	@Override
	public void onRegisterResult(Context context, int errorCode, XGPushRegisterResult registerMessage) {
		LogUtils.e("FengxzNotificationReceiver================onRegisterResult");

	}

	/**
	 * 设置标签结果
	 */
	@Override
	public void onSetTagResult(Context context, int errorCode, String tagName) {

	}

	/**
	 * 收到消息
	 */
	@SuppressLint("SimpleDateFormat")
	@Override
	public void onTextMessage(Context context, XGPushTextMessage message) {
		String content = message.getCustomContent();
		LogUtils.e("FengxzNotificationReceiver========onTextMessage======" + content);
		LogUtils.e("FengxzNotificationReceiver========isApplicationBroughtToBackground======" + isApplicationBroughtToBackground(context));
		NotificationBeen notificationBeen = JSON.parseObject(content, NotificationBeen.class);
		notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
		RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification);
		contentView.setTextViewText(R.id.titles, "风信子医生端");
		// contentView.setTextViewText(R.id.text, "有" + 1 +
		// "个用户对您的回答作出了评价，点击查看");
		contentView.setImageViewResource(R.id.image, R.drawable.icon);
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
		contentView.setTextViewText(R.id.time, format.format(new Date()));
		
		PendingIntent notifyPIntent = getDeleteIntent(context, notificationBeen);
		builder.setContentIntent(notifyPIntent);
		builder.setAutoCancel(true);
		builder.setContent(contentView);
		builder.setSmallIcon(R.drawable.icon);
		
		builder.setTicker("风信子医生端");
		Notification notification = builder.build();
		notification.defaults = Notification.DEFAULT_SOUND;

		SystemApplication.getInstance().notificationBeens.add(notificationBeen);
		SystemApplication.getInstance().notifications.add(notificationBeen);
		Intent intent = null;
		switch (notificationBeen.source) {
		case 102: // 用户评价问题的消息
			contentView.setTextViewText(R.id.text, "有" + getSizeFromList(102) + "个用户对您的回答作出了评价，点击查看");
			notiManager.notify(0, notification);
			break;
		case 103: // 系统通知的消息
			contentView.setTextViewText(R.id.text, "您有新的系统消息，点击查看");
			notiManager.notify(1, notification);
			break;
		case 104: // 用户追问医生的消息
			contentView.setTextViewText(R.id.text, "有" + getSizeFromList(104) + "位用户回复了您的解答，点击查看");
			notiManager.notify(2, notification);
			break;
		case 105: // 用户向指定医生提问的消息
			contentView.setTextViewText(R.id.text, "有" + getSizeFromList(105) + "条新问题指定向您提问，点击查看");
			notiManager.notify(3, notification);
			break;
		case 106: // 有即将超时的抢答的消息
			contentView.setTextViewText(R.id.text, "您有" + getSizeFromList(106) + "条抢答的问题即将超时，点击查看");
			notiManager.notify(4, notification);
			break;
		case 107: // 有即将超时的抢答的消息
			contentView.setTextViewText(R.id.text, notificationBeen.content);
			notiManager.notify(5, notification);
		
			break;
		case 109: 
			contentView.setTextViewText(R.id.text, notificationBeen.content);
			notiManager.notify(6, notification);
			
		}

		Intent intent1 = new Intent(MainActivity.ACTION_NAME);
		Bundle bundle = new Bundle();
		bundle.putSerializable("NotificationBeen", notificationBeen);
		intent1.putExtras(bundle);
		context.sendBroadcast(intent1);
	}

	/**
	 * 反注册结果
	 */
	@Override
	public void onUnregisterResult(Context context, int errorCode) {
		LogUtils.e("FengxzNotificationReceiver========onUnregisterResult======" + errorCode);
	}

	protected PendingIntent getDeleteIntent(Context context, NotificationBeen notificationBeen) {
		LogUtils.e("===========getDeleteIntent===============");
		Intent intent = null;
		if (!isApplicationBroughtToBackground(context)) {

			switch (notificationBeen.source) {
			case 102: // 用户评价问题的消息
				intent = new Intent(MainActivity.ACTION_NEW_REPLAY);
				intent.putExtra("type", 3);
				break;
			case 103: // 系统通知的消息
				intent = new Intent(MainActivity.ACTION_NEW_REPLAY);
				break;
			case 104: // 用户追问医生的消息
				intent = new Intent(MainActivity.ACTION_NEW_REPLAY);
				intent.putExtra("type", 2);
				break;
			case 105: // 用户向指定医生提问的消息
				intent = new Intent(MainActivity.ACTION_NEW_REPLAY);
				intent.putExtra("type", 1);
				break;
			case 106: // 有即将超时的抢答的消息
				intent = new Intent(MainActivity.ACTION_NEW_REPLAY);
				break;
			case 107: 
				intent = new Intent(MainActivity.ACTION_NAME);
				break;
			case 109: 
				intent = new Intent(MainActivity.ACTION_NAME);
				break;
			}
		} else {
			intent = new Intent(MainActivity.ACTION_NAME_OPEN_APP);
		}
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		Bundle bundle = new Bundle();
		bundle.putSerializable("QuestionBeen", notificationBeen);
		intent.putExtras(bundle);
		return PendingIntent.getBroadcast(context, 0, intent, 0);
	}

	/**
	 * 判断当前应用程序处于前台还是后台
	 */
	public static boolean isApplicationBroughtToBackground(final Context context) {
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;

	}

	private int getSizeFromList(int source) {
		int j = 0, k = 1;
		if (source == 102 || source == 104) {
			for (int i = 0, p = SystemApplication.getInstance().notifications.size(); i < p; i++) {
				if (!SystemApplication.getInstance().notifications.get(0).qId.equals(SystemApplication.getInstance().notifications.get(i).qId)) {
					k++;
				}
			}
			return k;
		} else {
			for (int i = 0, p = SystemApplication.getInstance().notifications.size(); i < p; i++) {
				if (SystemApplication.getInstance().notifications.get(i).source == source) {
					j++;
				}
			}
		}
		return j;
	}
}
